import { asyncRouterMap, constantRouterMap } from '@/router'
import store from '../index'
/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.indexOf(role) >= 0)
  } else {
    return true
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */
function filterAsyncRouter(asyncRouterMap, roles) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (hasPermission(roles, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, roles)
      }
      return true
    }
    return false
  })
  return accessedRouters
}
/**
 * 递归取出拥有权限的菜单 id，存放在数组中
 */
const permissionMenuIds = []
function getPermissionMenuId(menuTree) {
  menuTree.forEach((v) => {
    permissionMenuIds.push(v)
    if (v.children) {
      getPermissionMenuId(v.children)
    }
  })
}

/**
 * 递归将拥有菜单权限的菜单进行展示
 */
// const permissionTree = {}
function dealPermissionTree(tree) {
  tree.forEach((v) => {
    if (v.id) {
      // console.log(v)
      const len = permissionMenuIds.length
      for (let i = 0; i < len; i++) {
        if (v.id === permissionMenuIds[i].id) {
          v.meta.icon = permissionMenuIds[i].icon
          v.meta.title = permissionMenuIds[i].text
          v.hidden = false
          // if (v.id === '49294fa3-0622-4821-b800-3cbb70ef9fda'){
          //   console.log(v)
          // }
        }
      }
    }
    if (v.children) {
      dealPermissionTree(v.children)
    }
  })
}
const permission = {
  state: {
    routers: constantRouterMap,
    topRouters: [], // 激活顶部菜单时的子菜单
    topRoutersData: {}, // 激活顶部的菜单数据
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      // constantRouterMap 静态路由：例如：login, 404
      state.routers = constantRouterMap.concat(routers)
    },
    SET_TOP_ROUTERS: (state, routers) => {
      state.addRouters = routers.children
      state.topRoutersData = routers
      state.topRouters = constantRouterMap.concat(routers.children)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      // TODO: 处理菜单权限问题
      // console.log(store.getters.menus) // 拥有权限的菜单
      getPermissionMenuId(store.getters.menus)
      // console.log(permissionMenuIds)
      // 处理菜单权限树
      dealPermissionTree(asyncRouterMap)
      // console.log(asyncRouterMap)
      return new Promise(resolve => {
        const { roles } = data
        let accessedRouters
        if (roles.indexOf('admin') >= 0) {
          /**
           * 权限处理方式:
           * 方式1. 两个 tree 进行对比 所有路由配置 拥有权限的菜单 进行对比过滤
           * 方式2. 再次生成 可访问菜单
           */
          accessedRouters = asyncRouterMap
        } else {
          accessedRouters = filterAsyncRouter(asyncRouterMap, roles)
        }
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    },
    FilterTopRoutes({ commit }, data) {
      return new Promise(resolve => {
        // commit('SET_ROUTERS', data.children)
        commit('SET_TOP_ROUTERS', data)
        resolve()
      })
    }
  }
}

export default permission
